import 'dart:async';
import 'dart:convert';
import 'package:base_lib/index.dart';
import 'package:doctor_inquiry_lib/bus.dart';
import 'package:doctor_inquiry_lib/constant/constant.dart';
import 'package:flutter/services.dart';
import 'chat_list/entity/im_chat_list_entity.dart' as ChatListBean;
import 'chat_room_c2c/entity/msg_list_entity.dart' as MsgBean;

class InquiryPlugin {
  static const MethodChannel _channel =
      const MethodChannel('plugins.peach.com/inquiry');

  static num chatNextSeq = 0;
  static int chatCount = 99;

  static const String BUS_KEY_REFRESH_CHAT_LIST = 'BUS_KEY_REFRESH_CHAT_LIST';

  static const String BUS_KEY_REFRESH_CHAT_MSG = 'BUS_KEY_REFRESH_CHAT_MSG';

  static const String BUS_KEY_REFRESH_CHAT_MSG_LIST =
      'BUS_KEY_REFRESH_CHAT_MSG_LIST';

  static const String BUS_KEY_REFRESH_MSG_SOUND_PATH =
      'BUS_KEY_REFRESH_MSG_SOUND_PATH';

  static const String BUS_KEY_REFRESH_MSG_SEND_PROGRESS =
      'BUS_KEY_REFRESH_MSG_SEND_PROGRESS';

  static const String BUS_KEY_REFRESH_MSG_SEND_FAILED =
      'BUS_KEY_REFRESH_MSG_SEND_FAILED';

  List<ChatListBean.ImChatListEntity> chatList = [];

  InquiryPlugin._privateConstructor();

  static final InquiryPlugin _instance = InquiryPlugin._privateConstructor();

  factory InquiryPlugin() {
    return _instance;
  }

  static InquiryPlugin getInstance() => _instance;

  initMethodCallHandler() async {
    _channel.setMethodCallHandler((call) {
      var result;
      switch (call.method) {

        ///成功登录回调
        case "loginSuccess":
          initChatList();
          break;

        ///设置会话列表加载更多的起始行
        case "setChatListNextSeq":
          chatNextSeq = num.parse(call.arguments);
          FLog('setChatListNextSeq $chatNextSeq');
          break;

        ///刷新会话列表
        case "refChatList":
          FLog(call.method);
          List respList = json.decode(call.arguments);
          var tempList =
              respList.map((e) => ChatListBean.ImChatListEntity.fromJson(e));

          tempList.forEach((t) {
            chatList.removeWhere(
                (element) => element.conversationID == t.conversationID);
          });

          chatList..addAll(tempList);
          chatList.sort((a, b) =>
              a.getLastMsg.timestamp.compareTo(b.getLastMsg.timestamp));
          // FLog(json.encode(chatList));
          globalBus.send(BUS_KEY_REFRESH_CHAT_LIST, chatList.reversed);
          break;

        ///新消息，发送消息成功也会回调
        case "newMsg":
          var msgJson = json.decode(call.arguments);
          FLog('newMsg $msgJson');
          globalBus.send(
              BUS_KEY_REFRESH_CHAT_MSG, MsgBean.MsgEntity.fromJson(msgJson));
          break;

        ///刷新聊天页-空列表
        case "refreshChatUIEmpty":
          FLog(call.method);
          globalBus.send(BUS_KEY_REFRESH_CHAT_MSG_LIST, null);
          break;

        ///刷新聊天页
        case "refreshChatUI":
          List jsonMsgList = json.decode(call.arguments);
          // FLog('refreshChatUI $jsonMsgList');
          var tempMsgList =
              jsonMsgList.map((e) => MsgBean.MsgEntity.fromJson(e));
          // FLog('refreshChatUI $tempMsgList');
          globalBus.send(BUS_KEY_REFRESH_CHAT_MSG_LIST, tempMsgList);
          break;

        ///设置消息发送进度
        case "sendProgress":
          var proJson = call.arguments;
          FLog('sendProgress $proJson');
          globalBus.send(BUS_KEY_REFRESH_MSG_SEND_PROGRESS, proJson);
          break;

        ///发送消息失败
        case "sendFailed":
          var infoJson = call.arguments;
          FLog('sendFailed $infoJson');
          globalBus.send(BUS_KEY_REFRESH_MSG_SEND_FAILED, infoJson);
          break;

        case "refreshSoundPath":
          var infoJson = call.arguments;
          // FLog('refreshSoundPath $infoJson');
          globalBus.send(BUS_KEY_REFRESH_MSG_SOUND_PATH, json.decode(infoJson));

          break;

        default:
          result = null;
          break;
      }
      return result;
    });
  }

  initChatList() {
    chatNextSeq = 0;
    getChatList();
  }

  Future initSdk() async {
    final result =
        await _channel.invokeMethod('init', {'timAppID': Constant.TIM_APPID});
    return result;
  }

  ///登出
  Future logout(String userID, String userSign) async {
    final result = await _channel.invokeMethod('logout', {});
    return result;
  }

  ///登录
  Future login(String userID, String userSign) async {
    final result = await _channel.invokeMethod('login', {
      "userID": userID,
      "userSign": userSign,
    });
    return result;
  }

  ///判断是否为登录状态
  Future<bool> getIsLogin() async {
    final result = await _channel.invokeMethod('isLogin', {});
    return result;
  }

  ///获取会话列表
  Future getChatList() async {
    final result = await _channel.invokeMethod('getChatList', {
      "nextSeq": chatNextSeq,
      "count": chatCount,
    });
    return result;
  }

  ///获取会话详情
  Future getChat(String chatID) async {
    final result = await _channel.invokeMethod('getChat', {
      "chatID": chatID,
    });
    return result;
  }

  ///获取单聊聊天历史记录
  Future getC2CMsgList(String userID, int count, bool firstPull) async {
    final result = await _channel.invokeMethod('getC2CMsgList',
        {"userID": userID, "count": count, "firstPull": firstPull});
    return result;
  }

  ///设置单聊消息已读
  Future markC2CMessageAsRead(String userID) async {
    final result = await _channel.invokeMethod('markC2CMessageAsRead', {
      "userID": userID,
    });
    return result;
  }

  ///发送消息
  Future sendMsg(dynamic msg) async {
    final result = await _channel.invokeMethod('sendMsg', json.encode(msg));
    return result;
  }

  ///获取语音消息url
  Future getSoundPath(String msgID) async {
    final result = await _channel.invokeMethod('getSoundPath', {
      "msgID": msgID,
    });
    return result;
  }
}
